package com.tomas.demo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @author  Tomas
 * @date 2016-04-08 18:00:00
 * @what Common拦截器 打印请求URL和参数
 */
@Slf4j
@Component
public class CommonInterceptor implements HandlerInterceptor {
    private final String REQUEST_START_TIME="request_start_time";
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String queryString = request.getQueryString();
        log.info("请求开始 URL ='" + request.getMethod() + " " + request.getRequestURL() + (queryString != null && !queryString.isEmpty() ? "?" + queryString : "") + "'");
        request.setAttribute(REQUEST_START_TIME, System.currentTimeMillis());
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        Long start=(Long)request.getAttribute(REQUEST_START_TIME);
        log.info("请求结束 耗时: {} 毫秒",System.currentTimeMillis()-start);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        log.info("End render data.");
    }
}